package top.mccsdl.Acbot.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import org.springframework.stereotype.Service;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static top.mccsdl.Acbot.config.BotConfig.*;

@Service
public class TaskToken {

    private static final int REFRESH_BUFFER_SECONDS = 300; // 5 分钟，即 300 秒
    private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
//    public TaskToken() {
//        fetchAndScheduleRefresh();
//    }


    public void fetchAndScheduleRefresh() {
        try {
            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("appId", APPID);
            requestBody.put("clientSecret", APP_SECRET);

            // 发送 POST 请求
            HttpResponse response = HttpRequest.post(API_URL)
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .execute();

            if (response.isOk()) {
                // 解析响应结果
                JSONObject responseBody = new JSONObject(response.body());
                ACCESS_TOKEN = responseBody.getStr("access_token");
                EXPIRES_IN = responseBody.getInt("expires_in");
                TOKEN_FETCH_TIME = System.currentTimeMillis() / 1000;
                System.out.println(DateTime.now() + " 获取到的凭证: " + ACCESS_TOKEN);
                System.out.println(DateTime.now() + " 凭证有效时间: " + EXPIRES_IN + " 秒");

                // 在凭证过期后重新获取
                scheduler.schedule(this::fetchAndScheduleRefresh, EXPIRES_IN, TimeUnit.SECONDS);
            } else {
                System.err.println("请求失败，状态码: " + response.getStatus());
                System.err.println("响应内容: " + response.body());
                // 失败后设置一个固定的重试时间，这里设置为 5 分钟后重试
                scheduler.schedule(this::fetchAndScheduleRefresh, REFRESH_BUFFER_SECONDS, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            System.err.println("请求过程中出现异常: " + e.getMessage());
            // 出现异常后，也设置一个固定的重试时间
            scheduler.schedule(this::fetchAndScheduleRefresh, REFRESH_BUFFER_SECONDS, TimeUnit.SECONDS);
        }
    }
}
